<?php

namespace App\Morefun\Profile;

use App\Entities\Participant;
use App\Models\Participant\ParticipantService;
use Illuminate\Container\Container;
use Illuminate\Support\Arr;
use Ramsey\Uuid\Uuid;

class AppUserProfileSynchronizer
{
    const REDIS_KEY = '_profiles';
    const USER_RECORD = 'users:recorded';
    /**
     * @var \Redis
     */
    protected $redis;

    public function sync()
    {
        while (($record = $this->redis()->lPop(self::REDIS_KEY)) !== null) {
            var_dump($record);
            $profile = json_decode($record, true);

            if (!$profile) {
                continue;
            }

            $openId = Arr::get($profile, 'uid', '');
            $username = Arr::get($profile, 'username', '');
            $uniqueid = Arr::get($profile, 'uniqueid', '');
            $uniqueid = md5($uniqueid);
//            if (empty($openId) || empty($username)) {
//                continue;
//            }

            $participant = Participant::query()
                ->where('uniqueid', $uniqueid)
                ->first();

            if (null == $participant) {
                $participant = new Participant();
                $participant->fill(['created_at' => date('Y-m-d H:i:s')]);
            }

            $participant->fill([
                'openid' => $openId,
                'source' => Arr::get($profile, 'source', ''),
                'tenant_id' => Arr::get($profile, 'tenant_id', ''),
                'username' => $username,
                'nickname' => Arr::get($profile, 'nickname', ''),
                'avatar' => Arr::get($profile, 'avatar', ''),
                'mobile' => Arr::get($profile, 'mobile', ''),
                'uniqueid' => $uniqueid,
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            $participant->save();

            usleep(3000);
        }
    }

    public function resetEmpty()
    {
        $participants = Container::getInstance()->make(ParticipantService::class);
        $users = $participants->getParticipantByEmptyName();
        if($users){
            foreach ($users as $user){
                $this->redis()->hDel(self::USER_RECORD, $user->uniqueid);
                $user->delete();
            }
        }
        $userRecords = $this->redis()->hGetAll(self::USER_RECORD);
        if($userRecords){
            foreach ($userRecords as $userRecord => $value){
                $participant = $participants->getParticipantByUniqueID($userRecord);
                if(!$participant){
                    $this->redis()->hDel(self::USER_RECORD, $userRecord);
                }
            }
        }
    }

    protected function redis()
    {
        if (!$this->redis) {
            $this->redis = Container::getInstance()->make('redis');
        }

        return $this->redis;
    }

}
